﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Snowflake.Entity;
using System.Linq.Expressions;
using System.Data.Common;

namespace Snowflake.Gateway
{
    /// <summary>
    /// EntiyQuery Extensions
    /// </summary>
    public static class Extenstions
    {
        /// <summary>
        /// Creates Deletable EntityQuery
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity</typeparam>
        /// <param name="query">The query that will be coverted to Deleteable query</param>
        /// <returns>The deletable query</returns>
        public static EntityQuery<TEntity> Delete<TEntity>(this IQueryable<TEntity> query) where TEntity : EntityObject<TEntity>, new()
        {
            return new DeleteQuery<TEntity>(query);
        }

        /// <summary>
        /// Creates Updatable EntityQuery
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity</typeparam>
        /// <param name="query">The query that will be converted to Updateable query</param>
        /// <param name="update">The property that will be updated</param>
        /// <param name="additionalUpdate">Additional properties for update</param>
        /// <returns>The updateable query</returns>
        public static EntityQuery<TEntity> Update<TEntity>(this IQueryable<TEntity> query, Action<TEntity> update, params Action<TEntity>[] additionalUpdate) where TEntity : EntityObject<TEntity>, new()
        {
            EntityList<TEntity> entityList = new EntityList<TEntity>();
            TEntity entity = entityList.NewEntity();
            entityList.Insert(entity);
            entityList.AcceptChanges();


            List<Action<TEntity>> updateActions = new List<Action<TEntity>>();
            updateActions.Add(update);
            updateActions.AddRange(additionalUpdate);

            foreach (Action<TEntity> action in updateActions)
                action(entity);

            Dictionary<string, object> valuesForUpdate = entity.GetValuesForDbUpdate();
            return new UpdateQuery<TEntity>(query, valuesForUpdate);

        }
    }
}
